/**
 * @file: proc.cpp
 * @author: yumeng (imyumeng@qq.com)
 * @brief:
 * @version 0.1
 * @date: 2021-09-06
 *
 * @copyright Meng_Yu Copyright (c) 2021
 *
 * @history: v1.0.0.0 init first version. 2021-09-06
 * @history: v1.0.1.0 add com scan feature. 2021-09-06
 */
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <windows.h>
#include "proc.h"

struct proc_data g_data;

int Read_Tnifile(void)
{
	g_data.speed = GetPrivateProfileInt(INI_SEC_1, INI_SEC_1_1, 115200, INI_NAME);

	GetPrivateProfileString(INI_SEC_2, INI_SEC_X_1, "exit load mode", (LPTSTR)g_data.slot[0].open_str, STR_LEN, INI_NAME);
	GetPrivateProfileString(INI_SEC_2, INI_SEC_X_2, "enter load mode", (LPTSTR)g_data.slot[0].close_str, STR_LEN, INI_NAME);
	GetPrivateProfileString(INI_SEC_3, INI_SEC_X_1, "set pc switch off time=2.0", (LPTSTR)g_data.slot[1].open_str, STR_LEN, INI_NAME);
	GetPrivateProfileString(INI_SEC_3, INI_SEC_X_2, "set pc switch off time=5.0", (LPTSTR)g_data.slot[1].close_str, STR_LEN, INI_NAME);
	return 0;
}

int Write_Tnifile(void)
{
	char tmp_str[STR_LEN] = {0};
	sprintf(tmp_str, "%d", g_data.speed);
	WritePrivateProfileString(INI_SEC_1, INI_SEC_1_1, tmp_str, INI_NAME);

	WritePrivateProfileString(INI_SEC_2, INI_SEC_X_1, (LPTSTR)g_data.slot[0].open_str, INI_NAME);
	WritePrivateProfileString(INI_SEC_2, INI_SEC_X_2, (LPTSTR)g_data.slot[0].close_str, INI_NAME);
	WritePrivateProfileString(INI_SEC_3, INI_SEC_X_1, (LPTSTR)g_data.slot[1].open_str, INI_NAME);
	WritePrivateProfileString(INI_SEC_3, INI_SEC_X_2, (LPTSTR)g_data.slot[1].close_str, INI_NAME);
	return 0;
}

#ifdef DEBUG_EN
void InitConsoleWindow(void)
{
	int nCrt = 0;
	FILE* fp;
	AllocConsole();
	nCrt = _open_osfhandle((intptr_t)GetStdHandle(STD_OUTPUT_HANDLE), _O_TEXT);
	fp = _fdopen(nCrt, "w");
	*stdout = *fp;
	setvbuf(stdout, NULL, _IONBF, 0);
}

void PrintError(unsigned int dwErrcode)
{
	LPVOID lpMsgBuf;
	FormatMessage(
	    FORMAT_MESSAGE_ALLOCATE_BUFFER |
	    FORMAT_MESSAGE_FROM_SYSTEM |
	    FORMAT_MESSAGE_IGNORE_INSERTS,
	    NULL, dwErrcode,
	    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
	    (LPTSTR) &lpMsgBuf,
	    0, NULL );
	printf((LPCSTR)lpMsgBuf);
	LocalFree(lpMsgBuf);
}
#endif
